<?php
//by willson 105328468@qq.com 2014/10/8
class core extends wenyan {
	public $db;
	public $sign;
	public $member_id;
	public $ezr; //分页
	public $member_name;
	public $udid;
	public $nick_name;
	//public $company_name; //公司名称
	public $notify; //消息推送
	public $smarty;
	public $APP;
	public $ACT;
	public $service_tel; //客服电话
	public $ip; //IP地址
	public $tbp; //表名前缀
	public $easemob_org_name;
	public $easemob_app_name;
	public $easemob_client_id;
	public $easemob_client_secret;	
	public $city_id;
	public $configs; //配置参数
	public $request;
	public $domain;
	public $transfer_platforms;

	public function __construct() {
		parent::__construct();
		global $db, $smarty;
		global $act, $app ,$ezr;;
		global $notify;
		global $table_prefix;
		global $easemob_org_name, $easemob_app_name, $easemob_client_id, $easemob_client_secret;
		global $request;
		global $domain;
		global $transfer_platforms;
		$this->tbp = $table_prefix;
		$this->db = $db;
		$this->smarty = $smarty;
		$this->APP = $app;
		$this->ACT = $act;
		$this->request = $request;
		$this->ezr = $ezr;
		$this->domain = $domain;
		$this->transfer_platforms = $transfer_platforms;

		//加载配置参数
		$this->configs = array();

		$_config_sql = "SELECT name, memo, content FROM jf_config";
		$_configs = $this->db->get_results($_config_sql);
		if ($_configs) {
			foreach ($_configs as $_config) {
				$this->configs[$_config->name] = $_config->content;
			}
		}

		$this->shop_id = 0;
		$this->shop_type = 0;
		$this->member_id = 0;
		$this->member_name = '';
		$this->udid = '';
		$this->nick_name = '';
		//$this->company_name = '';
		$this->service_tel = '18027196538';
		//所在城市，简单处理。默认为广州
		$this->city_id = (isset($_SESSION['city_id']) && intval($_SESSION['city_id'])>0) ? intval($_SESSION['city_id']) : 440100;
		//消息推送
		$this->notify = $notify;
		//环信
		$this->easemob_org_name = $easemob_org_name;
		$this->easemob_app_name = $easemob_app_name;
		$this->easemob_client_id = $easemob_client_id;
		$this->easemob_client_secret = $easemob_client_secret;
		$reseller_id = (isset($_GET['reseller']) && trim($_GET['reseller'])) ? trim($_GET['reseller']) : '';
		if ($reseller_id) $_SESSION['reseller_id'] = $reseller_id;
		//ip
		$this->ip = ip();
		$this->sign = (isset($_GET['sign']) && trim($_GET['sign'])) ? trim($_GET['sign']) : '';
		//if ($this->sign) $this->_check_login(); //每次访问都需要检查是否登录了。
		$this->_check_login(); //取消了将sign复制到模板，所以每次都要检查登录
		
		//需要检查登录状态的方法
		$need_check_login_actions = array(
			'cart' => array(
				'jiesuan', 'order', 'order_complete'
				),		
			'order' => array(
				'detail'
				),
			'member' => array(
				'avatar','edit_info', 'favorite', 'add_delete_favorite', 'my_invite_user', 'commission_history', 
				'withdraw_apply', 'withdraw_history'
				),
			'recharge' => array(
				'buy', 'history'
				),
			'meal' => array(
				'buy', 'history', 'index'
				),
			//'index' => array('topic'),
		);
		//检查要登录的模块，如果没有授权，重新授权或重新登录
		foreach($need_check_login_actions as $app_name=>$actions) {
			if ($app == $app_name) {
				foreach ($actions as $action) {
					if ($act == $action) {
						$this->check_login();
					}
				}
			}
		}
		//日志
		$this->_handle_log();
	}

	//get user id from sign
	public function get_member_from_sign($sign) {
		$sql = "SELECT * FROM jf_member WHERE sign='{$sign}' LIMIT 1";
		//echo $sql;
		$row = $this->db->get_row($sql);
		if (!$row) {
			return false;
		}
		//写入session
		$_SESSION['member'] = $row;
		$this->member_id = $row->id;
		$this->member_name = $row->name;	
		$this->udid = $row->udid;	
		//print_r($row);
		//exit;

		return true;
	}
	
	//通过会员ID获取头像与昵称(若会员已开店铺即自动把店铺资料替换到当中)
	public function get_member_info($member_id){
		$avatar = "";
		$name = "";
		if ($member_id) {
			//先读取店铺
			$sql = "SELECT avatar, name FROM jf_member WHERE id='{$member_id}'";
			$row = $this->db->get_row($sql);
			if ($row) {
				//$row->avatar .= "!logo"; //logo缩略图 by willson 2015/9/6
				$avatar = add_domain($row->avatar);
				$name = $row->name;
			}
		}
		return array("avatar"=>$avatar, "name"=>$name);
	}
	
	//动态获取/设置会员属性
	//__set 魔术方法，当设置的属性不存在或者不可访问（private）时就会调用此函数
	public function __set($name, $value) {
		//不设置了
	}
	//__get 魔术方法，当获取的属性不存在或者不可访问（private）时就会调用此函数
	public function __get($name) {
		$perfix = substr($name, 0, 7);
		$property = substr($name, 7);
		if (empty($perfix) || empty($property) || $perfix!='member_' || !isset($_SESSION['member'])) return NULL;
		return isset($_SESSION['member']->$property) ? $_SESSION['member']->$property : NULL;
	}

	//是否登录
	public function _check_login() {
		//return $this->get_member_from_sign($this->sign);
		//已经登录 
		if (isset($_SESSION['member']) 
			&& is_object($_SESSION['member']) 
			&& isset($_SESSION['member']->id) 
			&& intval($_SESSION['member']->id)>0 
			&& isset($_SESSION['member']->sign) 
			&& $_SESSION['member']->sign  
		) {
			$this->member_id = $_SESSION['member']->id;
			$this->member_name = $_SESSION['member']->name;
			$this->udid = $_SESSION['member']->udid;
			//$this->shop_id = $_SESSION['member']->shop_id;
			//$this->member_obj = unserialize($_SESSION['member_obj']);
			//每次都刷新，debug使用
			//return $this->get_member_from_sign($this->sign);
			return true;
		} else {
			if (isset($_SESSION['member']->sign) && $_SESSION['member']->sign) {
				return $this->get_member_from_sign($_SESSION['member']->sign);
			} elseif ($this->sign) {
				return $this->get_member_from_sign($this->sign);
			} elseif (WX_LOGIN && $this->is_weixin()) { //以后直接在config修改WX_LOGIN的值就可以控制是否使用微信认证登录
				if (!$this->weixin_authed()) {
					$this->weixin_auth(); //弃用 wx_redirect_url.php
					return false;
				}
				return true;
			} else {
				return false;
			}
		}
	}

	//对是否登录函数的封装，如果登录了，则返回true，
	//否则，返回错误信息：-100，APP需检查此返回值，判断是否需要重新登录
	public function check_login(){
		if ($this->_check_login()) {
			return true;
		} else {
			error('请登录',-100);
		}
	}

	//日志
	private function _handle_log() {
		$log = m("log");
		$log->create();
	}

	//消息推送，先保存到数据库，再发送
	public function send_notify($message, $member_id=-1, $send_sms=false, $goto_target='') {
		$this->send_notify_sms($message, $member_id, false, array(), 0, $goto_target);
	}

	//消息推送与短息，先保存到数据库，再发送
	public function send_notify_sms($message, $member_id=-1, $send_sms=false, $sms_content=array(), $template_id=128241, $goto_target='') {
		$mobile = $udid = "";
		if ($member_id>0) {
			$sql = "SELECT udid, mobile FROM jf_member WHERE id='{$member_id}'";
			$member = $this->db->get_row($sql);
			if ($member) {
				$udid = $member->udid;
				$mobile = $member->mobile;
			}
		} else {
			$member_id = $this->member_id;
			$udid = $_SESSION['member']->udid;
			$mobile = $_SESSION['member']->mobile;
		}
		//写入消息表
		$message_type = "";
		if (strpos($message, "商品")) {
			$message_type = "goods";
		} elseif (strpos($message, "店铺")) {
			$message_type = "shop";
		} elseif (strpos($message, "订单")) {
			$message_type = "order";
		} else {
			$message_type = "html5";
		}
		$sql = "INSERT INTO jf_message(member_id, content, add_time, readed, message_type, goto_target) 
			VALUES('{$member_id}', '{$message}', '".time()."', '0', '{$message_type}', '{$goto_target}')";
		$this->db->query($sql);
		//发送推送
		$this->notify->send($udid, $message, "", "", array("type"=>"message"));
		//发送短信
		if ($send_sms && $mobile) {
			send_sms($mobile, $message, $template_id);
		}
	}

	public function is_weixin(){ 
		if (stripos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
			return true;
		} else {
			return false;
		}
	}
	
	//强制使用微信登录
	public function weixin_login() {
		if (!$this->weixin_authed(false)) {
			$this->weixin_auth();
		}
	}
	
	//$around 使用指定某些方法绕过
	public function weixin_authed($around=true) {
		if (isset($_SESSION['openid']) && trim($_SESSION['openid']) && isset($_SESSION['weixin'])) {
			return true;
		} else {
			if ($around) {
				$app = array('yydb', 'activity_zhuanpan');
				$act = array('weixin_auth', 'wx_login');
				if (isset($_GET['app']) && in_array($_GET['app'], $app)) return true;
				if (isset($_GET['act']) && in_array($_GET['act'], $act)) return true;
			}
			return false;
		}
	}
	
	public function weixin_auth() {
		$appid = WX_APPID;
		$appsecrect = WX_SECRET;
		$code = isset($_GET['code']) ? $_GET['code'] : "";
		//先获取code
		if ($code=='') {
			$_SESSION['weixin_url'] = $_SERVER['REQUEST_URI']; //登录后跳转的目标网址
			if (isset($_GET['app']) && isset($_GET['act']) && $_GET['app']=='core' && $_GET['app']=='weixin_auth' && trim($_SERVER['HTTP_REFERER'])) {
				$_SESSION['weixin_url'] = $_SERVER['HTTP_REFERER'];
				if (!trim($_SESSION['weixin_url'])) $_SESSION['weixin_url'] = $_SERVER['REQUEST_URI'];
			}
			if (!isset($_SESSION['weixin_url']) || !trim($_SESSION['weixin_url']))$_SESSION['weixin_url'] = 'wap.php';
			$redirect_url = urlencode("http://".$_SERVER['SERVER_NAME']."/api.php?app=core&act=weixin_auth");
			$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
			header("Location:{$url}");
			exit;
		} else {
			//用户授权
			$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecrect}&code={$code}&grant_type=authorization_code";
			$html = file_get_contents($url);
			$json = json_decode($html);
			//print_r($json);
			$openid = $json->openid;
			$_SESSION['openid'] = $openid;
			//获取用户信息
			$url = "https://api.weixin.qq.com/sns/userinfo?access_token={$json->access_token}&openid={$json->openid}&lang=zh_CN";
			$html = file_get_contents($url);
			$json = json_decode($html);
			//$json->nickname = preg_replace('/\xEE[\x80-\xBF][\x80-\xBF]|\xEF[\x81-\x83][\x80-\xBF]/', '', $json->nickname);
			//$json->nickname = addslashes($json->nickname);
			$sex = 1;
			if (strpos($html,'"sex":')!==false) $sex = $json->sex;
			if (is_numeric($sex)) $sex = intval($sex)==1 ? '男' : '女';
			$json->sex = $sex;
			$_SESSION['weixin'] = $json;
			header("Location:api.php?app=passport&act=login&openid={$openid}"); //增加openid参数是为了指定当前不是主动登录
		}
	}
	//设置分页的参数之类的
	public function setpages($data = array()) {
		$BRSR = (isset($_GET['BRSR']) && trim($_GET['BRSR'])) ? trim($_GET['BRSR']) : '';
		$this->smarty->assign('BRSR',$BRSR);
		//$this->ezr->num_results_per_page=10;
		//$this->ezr->num_browse_links = 10;
		$this->ezr->set_qs_val('app',$this->APP);
		$this->ezr->set_qs_val('act',$this->ACT);
		foreach ($data as $key=>$value) {
			$this->ezr->set_qs_val($key, $value);
			$this->smarty->assign($key, $value);
		}
	}
	//导航权限
	public function nav_power(){
		
	}
}
